package com.xingdata.jjxc.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.text.InputFilter;
import android.text.Spanned;
import android.widget.Toast;

import com.ab.activity.AbActivity;

// ��Ӣ���ַ����볤�ȿ���
public class NameLengthFilter implements InputFilter {

	int max_en;
	int res;
	private Activity avty;
	String regExp = "[\\u4e00-\\u9fa5]";

	public NameLengthFilter(Activity avty, int max_en, int res) {
		super();
		this.avty = avty;
		this.max_en = max_en;
		this.res = res;
	}

	@Override
	public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
		int destCount = dest.toString().length() + getChineseCount(dest.toString());
		int sourceCount = source.toString().length() + getChineseCount(source.toString());
		if (destCount + sourceCount > max_en) {
			Toast.makeText(avty, res, Toast.LENGTH_SHORT).show();
			return "";
		} else {
			return source;
		}
	}

	private int getChineseCount(String str) {
		int count = 0;
		Pattern p = Pattern.compile(regExp);
		Matcher m = p.matcher(str);
		while (m.find()) {
			for (int i = 0; i <= m.groupCount(); i++) {
				count = count + 1;
			}
		}
		return count;
	}
}
